package com.kingdee.eas.custom.aoyuan.aytime.bizbill.app;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import javax.ejb.*;
import java.rmi.RemoteException;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;

import com.kingdee.bos.*;
import com.kingdee.bos.util.BOSObjectType;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.bos.metadata.IMetaDataPK;
import com.kingdee.bos.metadata.query.util.CompareType;
import com.kingdee.bos.metadata.rule.RuleExecutor;
import com.kingdee.bos.metadata.MetaDataPK; //import com.kingdee.bos.metadata.entity.EntityViewInfo;
import com.kingdee.bos.framework.ejb.AbstractEntityControllerBean;
import com.kingdee.bos.framework.ejb.AbstractBizControllerBean; //import com.kingdee.bos.dao.IObjectPK;
import com.kingdee.bos.dao.IObjectValue;
import com.kingdee.bos.dao.IObjectCollection;
import com.kingdee.bos.service.ServiceContext;
import com.kingdee.bos.service.IServiceContext;

import com.kingdee.eas.basedata.org.HROrgUnitInfo;
import com.kingdee.eas.basedata.org.PositionFactory;
import com.kingdee.eas.basedata.org.PositionInfo;
import com.kingdee.eas.basedata.person.PersonFactory;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.custom.aoyuan.aytime.bizbill.AttenDetailFactory;
import com.kingdee.eas.custom.aoyuan.aytime.bizbill.CardRecordFactory;
import com.kingdee.eas.custom.aoyuan.aytime.bizbill.CardRecordInfo;
import com.kingdee.eas.custom.aoyuan.aytime.bizbill.HolidayBillCollection;
import com.kingdee.eas.custom.aoyuan.aytime.bizbill.HolidayBillEntryCollection;
import com.kingdee.eas.custom.aoyuan.aytime.bizbill.HolidayBillEntryFactory;
import com.kingdee.eas.custom.aoyuan.aytime.bizbill.HolidayBillEntryInfo;
import com.kingdee.eas.custom.aoyuan.aytime.bizbill.HolidayBillFactory;
import com.kingdee.eas.custom.aoyuan.aytime.bizbill.PersonOTBalanceCollection;
import com.kingdee.eas.custom.aoyuan.aytime.bizbill.PersonOTBalanceFactory;
import com.kingdee.eas.custom.aoyuan.aytime.bizbill.PersonOTBalanceInfo;

import java.lang.String;
import java.math.BigDecimal;

import com.kingdee.bos.metadata.entity.EntityViewInfo;
import com.kingdee.bos.metadata.entity.FilterInfo;
import com.kingdee.bos.metadata.entity.FilterItemInfo;
import com.kingdee.bos.metadata.entity.SelectorItemInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.bos.dao.IObjectPK;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.dao.query.IQueryExecutor;
import com.kingdee.bos.dao.query.QueryExecutorFactory;
import com.kingdee.bos.metadata.entity.SelectorItemCollection;
import com.kingdee.eas.custom.aoyuan.aytime.AYAttenBillStatusEnum;
import com.kingdee.eas.custom.aoyuan.aytime.TimeCardTypeEnum;

import com.kingdee.eas.custom.aoyuan.aytime.bizbill.HolidayBillInfo;
import com.kingdee.eas.hr.emp.PersonPositionCollection;
import com.kingdee.eas.hr.emp.PersonPositionFactory;
import com.kingdee.eas.hr.emp.PersonPositionInfo;
import com.kingdee.jdbc.rowset.IRowSet;

public class HolidayBillControllerBeanEx
		extends
		com.kingdee.eas.custom.aoyuan.aytime.bizbill.app.HolidayBillControllerBean {
	private static Logger logger = Logger
			.getLogger("com.kingdee.eas.custom.aoyuan.aytime.bizbill.app.HolidayBillControllerBeanEx");

	protected void _setStatus(Context ctx, String id,
			AYAttenBillStatusEnum newStatus) throws BOSException,
			EASBizException {
		super._setStatus(ctx, id, newStatus);
	}
	
	

	protected IObjectPK _submit(Context ctx, IObjectValue model)
			throws BOSException, EASBizException {
		HolidayBillInfo billInfo=(HolidayBillInfo) model;
		billInfo.setStatus(AYAttenBillStatusEnum.SUBMIT);
		return super._submit(ctx, model);
	}



	protected void _delete(Context ctx, IObjectPK pk) throws BOSException,
			EASBizException {
		super._delete(ctx, pk);
	}



	protected void _auditPass(Context ctx, IObjectValue model)
			throws BOSException {
		super._auditPass(ctx, model);
		HolidayBillInfo billInfo=getHolidayBillInfo(ctx,(HolidayBillInfo) model);
		
		if(billInfo==null)
		{
			logger.error("请假单设置审批通过失败！"+((HolidayBillInfo) model).getId().toString());
			return;
		}
		
		PersonOTBalanceCollection cos = getPersonOTBalanceCollection(ctx,billInfo);
		PersonOTBalanceInfo oTBalanceInfo = null;
		if (cos != null) {
			if (cos.size() > 0) {
				// 已经存在记录，不创建
				oTBalanceInfo = cos.get(0);
			} else {
				// 新增员工调休记录
				oTBalanceInfo = new PersonOTBalanceInfo();
				if (billInfo.getApplier() != null) {
					oTBalanceInfo.setPerson(billInfo.getApplier());
				}
			}
		}
		HolidayBillEntryCollection holidayBillEntryCollection = billInfo
				.getEntrys();
		try {
			for (int i = 0; i < holidayBillEntryCollection.size(); i++) {
				HolidayBillEntryInfo entry = holidayBillEntryCollection.get(i);
				if (entry.getHolidayType() == null) {
					continue;
				}

				// 调休
				if (entry.getHolidayType().getHtype().getValue() == 5) {
					oTBalanceInfo = sumPersonOTBalance(entry, oTBalanceInfo);
				} else if (entry.getHolidayType().getHtype().getValue() == 2
						&& entry.getSignedCard() != null) {
					// 补签卡
					CardRecordInfo cardInfo = new CardRecordInfo();
					if (billInfo.getApplier() != null) {
						cardInfo.setEmp(billInfo.getApplier());
						cardInfo.setBizDate(entry.getBizDate());
						cardInfo.setCardType(TimeCardTypeEnum.SIGNEDCARD);
						cardInfo.setBizTime(entry.getSignedCard());
						HROrgUnitInfo hrOrg=new HROrgUnitInfo();
						String hrOrgStr=getOrgByPerson(ctx,billInfo.getApplier().getId().toString());
						if(StringUtils.isNotEmpty(hrOrgStr))
						{
							hrOrg.setId(BOSUuid.read(hrOrgStr));
							cardInfo.setHROrgUnit(hrOrg);							
						}
						//记录那个请假分录插入
						cardInfo.setHolidayEntry(entry.getId().toString());
						CardRecordFactory.getLocalInstance(ctx).save(cardInfo);
					} else {
						//addMessage("没有请选择请假员工!");
					}
				}
			}
			PersonOTBalanceFactory.getLocalInstance(ctx).save(oTBalanceInfo);
			// 审批状态
			billInfo.setStatus(AYAttenBillStatusEnum.PASS);
			this.save(ctx, billInfo);
	    	//Calendar c = Calendar.getInstance();
	    	//c.setTime(billInfo.getStartdate());
	    	for(int i = 0; i < holidayBillEntryCollection.size(); i++)
	    	{
	    		AttenDetailFactory.getLocalInstance(ctx).calcOnePersonOneDay(billInfo.getApplier().getId().toString(), holidayBillEntryCollection.get(i).getBizDate());
        		//c.add(Calendar.DATE, 1);
	    	}
		} catch (EASBizException e) {
			e.printStackTrace();
			//addMessage("异常:" + e.getMessage());
		} catch (BOSException e) {
			e.printStackTrace();
			//addMessage("异常:" + e.getMessage());
		}
	}
	
	protected String getOrgByPerson(Context ctx, String id) {
		EntityViewInfo entityViewInfo = new EntityViewInfo();
		FilterInfo filterInfo = new FilterInfo();
		filterInfo.getFilterItems().add(
				new FilterItemInfo("id", id,
						CompareType.EQUALS));
		entityViewInfo.setFilter(filterInfo);
		IQueryExecutor iqec = QueryExecutorFactory.getLocalInstance(ctx, new MetaDataPK(    
                "com.kingdee.eas.custom.aoyuan.aytime.basedata.app",    
                "PersonHRQuery"));
		try {
			iqec.setObjectView(entityViewInfo);  
			IRowSet irow = iqec.executeQuery();
			if(irow.size()>0)
			{
				if(irow.next())
				{
					 String hrOrgId=irow.getString("HROrgUnit.id");
					 return hrOrgId;
				}
			}
		} catch (BOSException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public PersonOTBalanceInfo sumPersonOTBalance(HolidayBillEntryInfo entry,
			PersonOTBalanceInfo oTBalanceInfo) {

		BigDecimal totalHour = entry.getTotalhour();
		if (totalHour == null) {
			totalHour = new BigDecimal("0");
		}
		BigDecimal totaluse = oTBalanceInfo.getTotaluse();
		if (totaluse == null) {
			totaluse = new BigDecimal("0");
		}
		oTBalanceInfo.setTotaluse(totaluse.add(totalHour));
		return oTBalanceInfo;
		// PersonOTBalanceFactory.getRemoteInstance().save(oTBalanceInfo);
	}

	public PersonOTBalanceInfo sumPersonOTBalanceFail(
			HolidayBillEntryInfo entry, PersonOTBalanceInfo oTBalanceInfo) {
		BigDecimal totalHour = entry.getTotalhour();
		if (totalHour == null) {
			totalHour = new BigDecimal("0");
		}
		BigDecimal totaluse = oTBalanceInfo.getTotaluse();
		if (totaluse == null) {
			totaluse = new BigDecimal("0");
		}
		oTBalanceInfo.setTotaluse(totaluse.subtract(totalHour));
		return oTBalanceInfo;
	}

	protected void _auditFail(Context ctx, IObjectValue model)
			throws BOSException {
		super._auditFail(ctx, model);
		HolidayBillInfo billInfo = (HolidayBillInfo) model;
		try {
			// 审批状态
			billInfo.setStatus(AYAttenBillStatusEnum.AUDIT_FAIL);
			this.save(ctx, billInfo);

		} catch (EASBizException e) {
			e.printStackTrace();
		} catch (BOSException e) {
			e.printStackTrace();
		}

	}
	
	protected void _closeBill(Context ctx, IObjectValue model)
	throws BOSException {
		super._closeBill(ctx, model);
		HolidayBillInfo billInfo=getHolidayBillInfo(ctx,(HolidayBillInfo) model);
		
		if(billInfo==null)
		{
			logger.error("请假单作废失败！"+((HolidayBillInfo) model).getId().toString());
			return;
		}
		try {

			// 对所有假期类型为“调休”的分录，需要自动扣减（产生扣减记录）加班工时
			PersonOTBalanceCollection cos = getPersonOTBalanceCollection(ctx,
					billInfo);
			PersonOTBalanceInfo oTBalanceInfo = null;
			if (cos != null) {
				if (cos.size() > 0) {
					// 已经存在记录，不创建
					oTBalanceInfo = cos.get(0);
				} else {
					// 新增员工调休记录
					oTBalanceInfo = new PersonOTBalanceInfo();
					if (billInfo.getApplier() != null) {
						oTBalanceInfo.setPerson(billInfo.getApplier());
					}
				}
			}
			HolidayBillEntryCollection holidayBillEntryCollection = billInfo
					.getEntrys();
			for (int i = 0; i < holidayBillEntryCollection.size(); i++) {
				HolidayBillEntryInfo entry = holidayBillEntryCollection.get(i);
				if (entry.getHolidayType() == null) {
					continue;
				}

				// 调休
				if (entry.getHolidayType().getHtype().getValue() == 5) {
					oTBalanceInfo = sumPersonOTBalanceFail(entry, oTBalanceInfo);
				} else if (entry.getHolidayType().getHtype().getValue() == 2
						&& entry.getSignedCard() != null) {
					// 补签卡,去除保存时的插入的不签记录
					FilterInfo filter = new FilterInfo();
					filter.getFilterItems().add(
							new FilterItemInfo("holidayEntry", entry.getId()
									.toString(), CompareType.EQUALS));
					CardRecordFactory.getLocalInstance(ctx).delete(filter);
				}
			}
			PersonOTBalanceFactory.getLocalInstance(ctx).save(oTBalanceInfo);
			// 审批状态
			billInfo.setStatus(AYAttenBillStatusEnum.CLOSE);
			this.save(ctx, billInfo);
        	//Calendar c = Calendar.getInstance();
        	//c.setTime(billInfo.getStartdate());
	    	for(int i = 0; i < holidayBillEntryCollection.size(); i++)
	    	{
	    		AttenDetailFactory.getLocalInstance(ctx).calcOnePersonOneDay(billInfo.getApplier().getId().toString(), holidayBillEntryCollection.get(i).getBizDate());
        		//c.add(Calendar.DATE, 1);
	    	}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public HolidayBillInfo getHolidayBillInfo(Context ctx,HolidayBillInfo billInfo)
	{
		SelectorItemCollection sic = new SelectorItemCollection();
		sic.add("*");
		sic.add("applier.*");
		sic.add("entrys.*");
		sic.add("entrys.holidayType.*");
		try {
			return HolidayBillFactory.getLocalInstance(ctx).getHolidayBillInfo(new ObjectUuidPK(billInfo.getId()), sic);
		} catch (EASBizException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BOSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}

	public PersonOTBalanceCollection getPersonOTBalanceCollection(Context ctx,
			HolidayBillInfo billInfo) throws BOSException {
		if (billInfo == null) {
			return null;
		}
		EntityViewInfo evi = new EntityViewInfo();
		FilterInfo filter = new FilterInfo();
		if (billInfo.getApplier() != null) {
			filter.getFilterItems().add(
					new FilterItemInfo("person.id", billInfo.getApplier()
							.getId().toString(), CompareType.EQUALS));
		} else {
			return null;
		}
		evi.setFilter(filter);
		SelectorItemCollection sic = new SelectorItemCollection();
		sic.add("*");
		evi.setSelector(sic);
		return PersonOTBalanceFactory.getLocalInstance(ctx)
				.getPersonOTBalanceCollection(evi);
	}
}
